<template>
    <div>
        <input type="text" placeholder="请输入关键字" v-model="keyword">
        <input type="button" value="查找" @click="btnFind">
        <input type="button" value="新增" @click="btnAdd">
    </div>
    <table>
        <thead>
            <tr>
                <th>序号</th>
                <th>图书名称</th>
                <th>作者</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="item in books" :key="item.id">
                <td>{{ item.id }}</td>
                <td>{{ item.bookName }}</td>
                <td>{{ item.author }}</td>
                <td>
                    <input type="button" value="编辑" @click="btnEdit(item.id)">
                    <input type="button" value="删除" @click="btnDel(item.id)">
                </td>
            </tr>
        </tbody>
    </table>
</template>

<script setup>
import { onMounted , reactive, ref } from "vue";
import { getAll,delItem } from '@/api/bookApi.js'
import { useRouter } from "vue-router";

let router = useRouter()

// --- 响应式数据 开始 ---
let books = reactive([])
let keyword = ref('')
// --- 响应式数据 结束 ---


// --- 生命周期函数 开始 ---
onMounted( async () => {
    let data = await getAll()
    // console.log(data.data);
    books.push(...data.data)
})
// --- 生命周期函数 结束 ---


// --- 动作逻辑 开始 ---
function btnAdd() {
    // console.log('新增');
    router.push('/bookadd')
}

function btnEdit(id) {
    // console.log('编辑');
    router.push(`/bookedit/${id}`)
}

async function btnDel(id) {
    // console.log('删除');
    if(confirm('你确定要删除吗？')){
        let data = await delItem(id)
        // console.log(data);
        if(data.code === 1000){
            let index = books.findIndex(item => item.id === id)
            books.splice(index,1)
        }
    }
}

async function btnFind() {
    // console.log('查找');
    let newKeyword = keyword.value.trim()
    let data = await getAll(newKeyword)
    books.splice(0)
    books.push(...data.data)
}

// --- 动作逻辑 结束 ---
</script>